<template>
  <div>
    <div class="title">商品管理</div>
    <SelectBar :barData="['全部商品', '发布商品']" v-model="selectIndex" @handleSelect="handleSelect"></SelectBar>

    <div v-show="selectIndex===0" style="background-color: #fff;width: 100%;">
      <div style="padding: 10px 10px 10px 10px; display: flex;">
        <el-input
          v-model="nameInput"
          placeholder="输入商品名称"
          style="width: 300px;"
        >
          <i slot="append" class="el-icon-search" @click="searchGoods()" style="align-items: center;font-size: large;"></i>
        </el-input>
        <div style="margin-left: auto;">
          <el-button type="danger" @click="batchDelete" >批量删除</el-button>
        </div>
      </div>
      
      <div style="padding:10px;margin-bottom: 100px;margin-right:50px ;">
        <!-- biaoge -->
        <el-table
          ref="multipleTable"
          border
          :data="tableData"
          tooltip-effect="dark"
          @selection-change="handleSelectionChange"
          style="width: 100%"
        >
          
          <el-table-column label="商品信息" width="500" >
            <template slot-scope="scope">
              <div style=" display: flex;align-items: center;">
                <el-image
                style="width: 150px; height: 80px"
                :src="scope.row.image"
                fit="scale-down"></el-image>
                <div>
                  {{ scope.row.name }}<br/>
                  <div style="color: rgb(162, 162, 162);">
                  商品编号:{{ scope.row.id }}</div>
                </div>
              </div>
              
            </template>
          </el-table-column>
          <el-table-column label="价格(元)" width="120">
            <template slot-scope="scope">
              <div>{{ scope.row.price.toFixed(2) }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="stock" label="库存" width="120">
          </el-table-column>
          <el-table-column prop="salesVolume" label="销量" width="120">
          </el-table-column>
          <el-table-column label="上架时间" width="200">
            <template slot-scope="scope">
              <div>{{ scope.row.createTime  }}</div>
              <div v-if="scope.row.status===1" style="color:rgb(127, 255, 187);">在售中</div>
              <div v-else-if="scope.row.status === 2" style="color:rgb(255, 47, 36);">库存不足</div>
              <div v-else-if="scope.row.status === 0" style="color:rgb(125, 125, 125);">停售中</div>
              
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template slot-scope="scope">
              <span class="handle" @click="edit(scope.row.id)">编辑</span>
              <!-- <span class="handle">降价</span> -->
              <span v-if="scope.row.status===1" @click="handleStatus(0, scope.row.id)" class="handle">停售</span>
              <span v-else-if="scope.row.status === 0" @click="handleStatus(1, scope.row.id)" class="handle">起售</span>
              </template>
          </el-table-column>
          <el-table-column label="多选" type="selection" width="55"> </el-table-column>
          
          
        </el-table>
        <el-pagination
          style="margin-top: 20px;"
          :page-size="pageSize"
          layout="total, prev, pager, next"
          :total="pageTotal" :hide-on-single-page="true"
          @current-change="handlePageChange"
          >
        </el-pagination>
      </div>
    </div>


    <div v-show="selectIndex===1">
      <!-- 商品类目 -->

      <!-- <div class="box">
        <div style="display: flex;">
          <el-input
            v-model="input"
            placeholder="搜索你想发布的商品类目"
            
            suffix-icon="el-icon-search"
            style="width: 300px;"
          >
          </el-input>
          <div style="margin-left: auto;">
            <el-button type="danger" >批量删除</el-button>
          </div>
        </div>
        <div style="display: flex;">
          <div class="category">
            一级类目<br/>
            <el-input
            v-model="input"
            placeholder="搜索"
            
            suffix-icon="el-icon-search"
            style="width: 300px; margin: 10px 0 10px 0;"
          ></el-input>
          </div>
          <div class="category">

          </div>
          <div class="category">
          </div>
        </div>
        <span style="margin: 10px;">当前选择商品类目:</span> 
      </div> -->
      
      <!-- 销售信息 -->
      <div class="box">
        <span style="margin: 15px;font-size: larger;">销售信息</span>
        <div style="display: flex;"> 
          <div :class="{'shop-card':goodsData.specMethod===2,'selected-shop-card':goodsData.specMethod===1}"
            @click="changeSpecMethod(1)"
          >
            <div style="margin:5px 5px 3px 5px;font-weight: bold;">
              单规格商品<br/>
            </div>
            <span style="color:rgb(162, 162, 162); margin:0px 5px;">一个商品</span>
            <div class="icon-box">
              <i class="el-icon-shopping-bag-2" style="font-size: 50px;"></i>
            </div>
          </div>
          
          <div :class="{'shop-card':goodsData.specMethod===1,'selected-shop-card':goodsData.specMethod===2}"
            @click="changeSpecMethod(2)">
            <div style="margin:5px 5px 3px 5px;font-weight: bold;">
              多规格商品<br/>
            </div>
            <span style="color:rgb(162, 162, 162); margin:0px 5px;">多分类商品</span>
            <div class="icon-box">
              <i class="el-icon-shopping-bag-1" style="font-size: 50px;;"></i>
            </div>
          </div>
        </div>
        <!-- 详细规格 -->
        <div v-for="(item,index) in goodsData.specs" :key="index" style="display: flex;align-items:center;">
          <div class="spec-box">规格名称 <el-input v-model="item.name" 
            placeholder="请输入名称" style="margin:0 20px;width: 200px;"></el-input></div>
          <div class="spec-box">规格单价 <el-input v-model.number="item.price" 
            placeholder="请输入单价" style="margin:0 20px;width: 200px;"></el-input>元</div>
          <div class="spec-box">规格数量 <el-input v-model.number="item.stock" 
            placeholder="请输入数量" style="margin:0 20px;width: 200px;"></el-input>件</div>
          <i class="el-icon-delete" @click="changeSpec(index)" v-show="goodsData.specMethod === 2&& goodsData.specs.length>1"></i>
        </div>
        <el-button style="margin: 10px;" type="primary" @click="changeSpec(-1)" v-show="goodsData.specMethod===2">+添加规格</el-button>
        
      </div>
      <!-- 基础信息 -->
      <div class="box">
        <span style="margin: 10px;font-size: larger;">基础信息</span>
        <div class="goods-box">商品标题 <el-input v-model="goodsData.name" placeholder="请输入名称" style="margin:0 20px;width: 350px;"></el-input></div>
        <div class="goods-box">商品标签 <el-input v-model="goodsData.tag" placeholder="请输入标签" style="margin:0 20px;width: 350px;"></el-input></div>
        <div style="display: flex;margin: 30px 10px 20px 10px;">商品主图  
          <div style="color:rgb(162, 162, 162);margin-left: 20px;">
            <UploadComponent :image-limit="1" @handleUpload="handleMainUpload" ref="mainUpload"></UploadComponent>
            *商品图片单张大小不能超过3M,最多上传1张,支持JPG、PNG等格式
          </div>
        </div>
       
      </div>
      <!-- 物流信息 -->
      <div class="box"> 
        <span style="margin: 10px;font-size: larger;">物流信息</span>
        <div class="goods-box">提取方式 
          <el-radio-group v-model="goodsData.express" style="margin:20px;">
            <el-radio :label="1">使用物流配送</el-radio>
            <el-radio :label="2">指定地点自提:
              <el-input v-model="goodsData.pickup" placeholder="请输入自提点" style="margin:0 20px;width: 350px;"></el-input>
            </el-radio>
          </el-radio-group>
        </div>
        <div class="goods-box">区域限发 
          <el-radio-group v-model="goodsData.scope" style="margin:20px;">
            <el-radio :label="1">校内区域发</el-radio>
            <el-radio :label="2" style="margin-left:14px;">校外区域发</el-radio>
          </el-radio-group>
        </div>
      </div>
      <!-- 支付信息 -->
      <div class="box"> 
        <span style="margin: 10px;font-size: larger;">支付信息</span>
        <div class="goods-box">支付方式 
          <el-radio-group v-model="goodsData.payMethod" style="margin:20px;">
            <el-radio :label="1">微信</el-radio>
            <el-radio :label="2">支付宝</el-radio>
            <el-radio :label="3">银联</el-radio>
          </el-radio-group>
        </div>
        <div class="goods-box">电子发票 
          <el-radio-group v-model="goodsData.invoice" style="margin:20px;">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false" style="margin-left:14px;">否</el-radio>
          </el-radio-group>
        </div>
      </div>
      <!-- 图文描述 -->
      <div class="box">
        <span style="margin: 20px;font-size: larger;">图文描述</span>
        <div style="display: flex;margin: 30px 10px 20px 10px;">商品视频  
          <div style="color:rgb(162, 162, 162);margin-left: 20px;">
            <UploadComponent :image-limit="1" @handleUpload="handleVideoUpload" ref="videoUpload"></UploadComponent>
            *时长&lt;=60s,微视频建议15s。
          </div>
        </div>
        <div style="display: flex;margin: 30px 10px 20px 10px;">详细图片  
          <div style="color:rgb(162, 162, 162);margin-left: 20px;">
            <UploadComponent :image-limit="12" @handleUpload="handleImagesUpload" ref="imagesUpload"></UploadComponent>
            *商品图片单张大小不能超过3M，最多上传12张，支持JPG、PNG等格式
          </div>
        </div>
        <div style="display: flex;margin: 30px 10px 20px 10px;">详细描述
          <el-input
            type="textarea"
            style="margin:0 20px 0 30px; width: 400px;"
            :rows="4"
            v-model="goodsData.description"
            placeholder="请输入内容"
            >
          </el-input>
        </div>
      </div>
      <!-- 售后服务 -->
      <div class="box"> 
        <span style="margin: 10px;font-size: larger;">售后服务</span>
        <div class="goods-box">服务详情 
          <el-radio-group v-model="goodsData.service" style="margin:20px;">
            <el-radio label="保修服务">保修服务</el-radio>
            <el-radio label="退换货承诺">退换货承诺</el-radio>
            <el-radio label="七天无理由承诺">七天无理由承诺</el-radio>
          </el-radio-group>
        </div>
        <div class="goods-box">上架时间 
          <el-radio-group v-model="goodsData.loadTime" style="margin:20px;">
            <el-radio :label="0">立即上架</el-radio>
            <el-radio :label="loadTime">定时上架
              <el-date-picker
              type="datetime"
              placeholder="选择日期时间"
              style="margin:0 20px;"
              align="right"
              v-model="loadTime">
              </el-date-picker>
            </el-radio>
          </el-radio-group>
        </div>
      </div>


      <el-button size="large" @click="submit" style="float: right;width: 90px; height: 40px;" type="primary">确认</el-button>
    </div>



  </div>
</template>

<script>
import SelectBar from '@/components/SelectBar.vue';
import UploadComponent from '@/components/UploadComponent.vue';
import { addGoods, getPage,getGoods,modifyGoods,del,changeStatus } from '@/api/goodsManage';
import _ from 'lodash'
export default {
  data() {
    
    return {
      selectIndex: 0,
      //barData:['全部商品','发布商品'],
      tableData: [],
      multipleSelection: [],
      input: '',
      goodsData:{
        name: '',
        tag: '',
        image: '',
        express: 1,
        scope: 1,
        pickup: '',
        description: '',
        service: '',
        video: '',
        payMethod: 1,
        invoice: false,
        specs: [{ name: '', price: '', stock: '' }],
        shopImages: [],
        specMethod: 1,
        loadTime: ''
      },
      initialData:{
        name: '',
        tag: '',
        image: '',
        express: 1,
        scope: 1,
        pickup: '',
        description: '',
        service: '',
        video: '',
        payMethod: 1,
        invoice: false,
        specs: [{name:'',price:'',stock:''}],
        shopImages: [],
        specMethod: 1,
        loadTime: ''
      },
      loadTime:'',
      pageTotal: 0,
      pageSize:10,
      page:1,
      nameInput:'',
      isEdit:false
      
    };
  },
  methods:{
    searchGoods(){
      //console.log('click suffix')
      this.goodsQueue()
    },
    handleSelect(index){
      if(index===0){
        //深拷贝
        this.goodsData=_.cloneDeep(this.initialData)
        this.clearUpload()
      }
      this.selectIndex=index
      this.isEdit=false
    },
    changeSpec(idx){
      if(idx===-1) this.goodsData.specs.push({ name: '', price: '', stock: '' })
      else this.goodsData.specs.splice(idx,1)
    },
    submitCheck(){
      let obj=this.goodsData
      if(obj.name.replace(/\s/g, "").length<2){
        this.$message.error('商品名称不能小于2个字符')
        return false
      }
      if(obj.tag.replace(/\s/g, "").length <1){
        this.$message.error('商品标签不能为空')
        return false
      }
      if (obj.description .replace(/\s/g, "").length < 1) {
        this.$message.error('商品详情不能为空')
        return false
      }
      if(obj.image===''){
        this.$message.error('商品主图片不能为空')
        return false
      }
      if(obj.express===2&&obj.pickup.replace(/\s/g, "").length < 1){
        this.$message.error('请输入自提点')
        return false
      }
      if (obj.video === '') {
        this.$message.error('商品视频不能为空')
        return false
      }
      if (obj.shopImages.length <1) {
        this.$message.error('商品详细图片不能为空')
        return false
      }
      if(obj.service===''){
        this.$message.error('请选择售后服务')
        return false
      }
      let flag=true
      obj.specs.forEach(spec => {
        if(spec.name.replace(/\s/g, "").length < 1){
          this.$message.error('规格名称不能为空')
          flag=false
        }
        if (isNaN(parseFloat(spec.price))) {
          this.$message.error('规格价格必须为数字')
          flag = false
        }
        if (parseInt(spec.stock).toString() !== spec.stock.toString()) {
          this.$message.error('规格数量必须为整数')
          flag = false
        }
      })
      if(!flag)return false
      return true
    },
    async submit(){
      //检验
      if(!this.submitCheck()){
        return
      }
      //新增还是编辑
      let res;
      if(this.isEdit){
        res= await modifyGoods(this.goodsData)
      }
      else {
        res = await addGoods(this.goodsData)
      }
      
      if(res.data.code===1){
        this.$message('操作成功')
        this.handleSelect(0)
        this.goodsQueue()
      }
    },
    handlePageChange(val){
      this.page=val
      this.goodsQueue()
    },
    handleSelectionChange(val){
      this.multipleSelection=val.map((obj)=>{
        return obj.id
      })
    },

    async goodsQueue(){
      let res=await getPage(this.nameInput, this.page, this.pageSize)
      //console.log(res)
      this.pageTotal = res.data.data.total
      this.tableData = res.data.data.records
    },
    handleMainUpload(urls){
      if(urls.length===0)this.goodsData.image=''
      else this.goodsData.image = urls[0].image
    },
    handleVideoUpload(urls){
      if (urls.length === 0) this.goodsData.video = ''
      else this.goodsData.video = urls[0].image
    },
    handleImagesUpload(urls){
      this.goodsData.shopImages=urls
    },
    clearUpload(){
      this.$refs.mainUpload.clearUpload()
      this.$refs.videoUpload.clearUpload()
      this.$refs.imagesUpload.clearUpload()
      
    },
    initUpload(){
      this.$refs.mainUpload.initImages(this.goodsData.image)
      this.$refs.videoUpload.initImages(this.goodsData.video)
      this.$refs.imagesUpload.initImages(this.goodsData.shopImages)
    },

    async edit(id){
      let res=await getGoods(id)
      this.goodsData=res.data.data
      this.initUpload()
      if(this.goodsData.specs.length===1){
        this.goodsData.specMethod=1
      }
      else this.goodsData.specMethod=2
      // console.log(this.goodsData)
      this.selectIndex=1
      this.isEdit=true
    },
    async batchDelete(){
      let res= await del(this.multipleSelection)
      if(res.data.code===1){
        this.$message('删除成功')
      }
      this.$refs.multipleTable.clearSelection()
      await this.goodsQueue()
    },
    async handleStatus(status,id){
      await changeStatus(status,id)
      this.goodsQueue()
    },
    changeSpecMethod(index){
    
      if(index===1){
        this.goodsData.specs.splice(1)//删除下标为0后面的
      }
      this.goodsData.specMethod=index
      this.$forceUpdate()
    }


  },
  mounted() {
    this.goodsQueue()
  },
  components:{
    SelectBar,UploadComponent
  }
};
</script>

<style scoped>
.title{
  font-size: larger;
  margin: 10px 10px 30px 0;
  /* font-family: Microsoft YaHei; */
}
.bar-father {
  display: flex;
  /* margin-left: 10px; */
}
.selected-bar {
  background-color: #fff;
  /* margin: 10px 10px; */
  padding: 5px 0px;
  border-bottom: #9370db solid 2px;
}
.bar {
  /* margin: 20px 20px; */
  padding: 15px 35px;
}
.bar-padding {
  background-color: #fff;
  border-radius: 5px 5px 0 0;
  padding: 10px 35px 15px 35px;
}
.handle{
  margin:0 10px;
  color: #409EFF;
  /* 鼠标移上去有手形 */
  cursor: pointer
}
.box{
  width: 1200px;
  margin: 0px 10px 20px 10px;
  padding: 10px 10px 30px 10px; 
  background-color: #fff;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
}
.category{
  margin: 20px 0 10px 0;
  padding: 10px;
  width: 300px;
  height: 550px;
  border: #d6d6d6 solid 1px;

}
.shop-card{
  margin: 30px 10px 10px 10px;
  width: 195px;
  height: 92px;
  box-sizing: border-box;
  border: 0.5px solid #E5E5E5;
  position: relative;
  padding: 5px;
}
.selected-shop-card{
  margin: 30px 10px 10px 10px;
  width: 195px;
  height: 92px;
  box-sizing: border-box;
  border: 0.5px solid #409EFF;
  position: relative;
  color: #409EFF;
  background: #F3F7FE;
  padding: 5px;
}
.icon-box{
  position: absolute;
  bottom: 0%;
  right: 0%;
}
.spec-box{
  display: flex;
  margin:10px 20px 10px 10px ;
  align-items:center;
}
.goods-box{
  display: flex;
  margin: 10px 10px 20px 10px;
  align-items:center;
}
</style>